package entity

import (
	"github.com/jinzhu/gorm"
	"time"
	"yak.admin/src/util"
)

const (
	AdminNormal        = 1
	AdminSuper         = 2
	AdminDefaultAvatar = "avatar/admin/default.jpg"
)

var TypeLabels = map[int]string{
	util.TypeDrug:   "药品",
	util.TypeDevice: "医疗器械",
}

type Admin struct {
	Id            int    `gorm:"AUTO_INCREMENT"`
	Username      string `gorm:"type:varchar(128);unique"`
	Password      string `gorm:"type:varchar(255)"`
	Nickname      string `gorm:"type:varchar(128)"`
	LastLoginTime int64
	Type          int
	Group         int
	Province      string `gorm:"type:varchar(16)"`
	City          string `gorm:"type:varchar(16)"`
	County        string `gorm:"type:varchar(16)"`
	Address       string `gorm:"type:varchar(255)"`
	SendSms       int
	Phone         string `gorm:"type:varchar(11)"`
	Avatar        string `gorm:"type:varchar(255);default(avatar/admin/default.jpg)"`
}

func (admin *Admin) TableName() string {
	return "admin"
}

func (admin *Admin) GetPassword(password string) string {
	authKey := util.GetSystemValue("auth_key")
	return util.Md5(password + authKey)
}

func (admin *Admin) SetPassword(password string) {
	admin.Password = admin.GetPassword(password)
}

func (admin *Admin) CheckPassword(password string) bool {
	return admin.Password == admin.GetPassword(password)
}

func (admin *Admin) IsSuper() bool {
	return admin.Group == AdminSuper
}

func (admin *Admin) RefreshLoginTime() {
	admin.LastLoginTime = time.Now().Unix()
}

func (admin *Admin) BeforeCreate(scope *gorm.Scope) error {
	defaultPassword := util.GetSystemValue("default_password")
	_ = scope.SetColumn("password", admin.GetPassword(defaultPassword))
	_ = scope.SetColumn("last_login_time", time.Now().Unix())
	_ = scope.SetColumn("avatar", AdminDefaultAvatar)
	return nil
}
